package com.duke.payphone.acct;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * Displays a list of all the users registered credit cards (this should be
 * saved in globalvars)
 * Select on individual credit card (can edit, delete)
 * 
 * Buttons: [Edit], Delete, and New (CreditNewActivity)
 * - don't enable the edit/delete functionality just yet
 * 
 * - figure out how to implement these features...
 * 
 * @author Michael
 * 
 */
public class CreditListActivity extends Activity {

    private Global globalvars;

    private ListView cardListView;
    private ArrayAdapter<String> listAdapter;

    private Activity myself;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credit_list);

        myself = this;

        globalvars = (Global) getApplicationContext();
        cardListView = (ListView) findViewById(R.id.lv_cards);

        // populateList();
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_credit_list, menu);
        // return true;
        return false;
    }

    @Override
    public void onResume () {
        super.onResume();
        populateList();
    }

    /**
     * user presses "new" button
     * 
     * @param v
     */
    public void executeNew (View v) {
        Intent toCreditNew = new Intent(this, CreditNewActivity.class);
        startActivity(toCreditNew);
        // finish();
    }

    /**
     * user presses "back" button
     * 
     * @param v
     */
    public void executeBack (View v) {
        finish();
    }

    /**
     * populates the credit card list - runs on create
     * 
     * @param v
     */
    public void populateList () {

        // check validity
        if (true) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onListValid(response);
                    }
                    else {
                        onListInvalid(response); // should not happen
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }

    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {
        Map<String, Serializable> request = MapFactory.createTransmitMap("cardlist");
        return request;
    }

    /**
     * load items from the credit card list
     * 
     * @param response
     */
    private void onListValid (Map<String, Serializable> response) {

        if (response.containsKey("cardlist")) {

            String[] cardArray = (String[]) response.get("cardlist");

            ArrayList<String> cardList = new ArrayList<String>();
            cardList.addAll(Arrays.asList(cardArray));

            // Create ArrayAdapter using the card list.
            listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, cardList);

            // Set the ArrayAdapter as the ListView's adapter.
            cardListView.setAdapter(listAdapter);

            // set listener on the card listview
            cardListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick (AdapterView<?> arg0, View view, int position, long id) {
                    Object o = cardListView.getItemAtPosition(position);
                    String card = o.toString();

                    // pass intent to cardedit screen (do NOT finish() this
                    // activity)
                    Intent toEditCard = new Intent(myself, CreditEditActivity.class);
                    toEditCard.putExtra("cardid", card);
                    startActivity(toEditCard);

                }
            });

            Toast.makeText(globalvars, "Card list loaded.", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Note: this should never happen
     * 
     * @param response
     */
    private void onListInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Card list load failed. Please try again.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
